var domains = ["0w0.cc", "maid.tw", "goo.gl", "is.gd", "faryne.at"];

function shortener_onclick (info, tab) {
  var mId = parseInt(info.menuItemId, 10) - 3;
  var url = info.pageUrl;
  var domain  = domains[mId];
  
  doRequest(domain, url);
}

function doRequest (domain, url) {
  var request_uri = 'http://ha2.tw/rest/short_url/shorten.json?url='+encodeURIComponent(url)+'&domain='+domain;
  var xhr = new XMLHttpRequest();
  try {
    xhr.onreadystatechange = function(state) {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          var obj = JSON.parse(xhr.responseText);
          var notification = webkitNotifications.createNotification(
            'small1.png',
            '縮好了！',
            "短網址："+obj.shortUrl+"; 並且複製到剪貼簿了！"
          );
          notification.onclick = function (e) {
            window.open(obj.shortUrl);
            e.currentTarget.cancel();
          };
          
          
          // 複製到剪貼簿
          bg = chrome.extension.getBackgroundPage();
          clipboardholder= bg.document.getElementById("clipboardholder");
          clipboardholder.style.display = "block";
          clipboardholder.value = obj.shortUrl;
          clipboardholder.select();
          bg.document.execCommand("Copy");
          clipboardholder.style.display = "none";

          //
          notification.show();
        }
      }
    }

    xhr.onerror = function(error) {
      var notification = webkitNotifications.createNotification(
        'small1.png', 
        '發生錯誤了',
        JSON.stringify(error)
      );
      console.log("發生錯誤了......" + JSON.stringify(error));
    }

    xhr.open("GET", request_uri, true);
    xhr.send({});
  } catch(e) {
    console.log("發生例外狀況： " + e);
  }
}

function trackShortUrl (info, tab) {
  var url = info.selectionText !== undefined ? info.selectionText : info.linkUrl;
  if (url.search("http://") === false && url.search("http://") === false) {
    var url = "http://"+url;
  }
  
  $.ajax({
    type: 'get',
    
    url:  'http://ha2.tw/rest/webheader/parse.json?url='+encodeURIComponent(url),
    success: function(response) {
      var redirect_url = false;
      for (var i in response.header) {
        if (response.header[i]['type'] === 'Location') {
          redirect_url = response.header[i].value;
          break;
        }
      }
      if (redirect_url !== false) {
        var notification = webkitNotifications.createNotification(
          'small1.png',
          '查到了短網址導向的目標了',
          redirect_url
        );
      } else {
        var notification = webkitNotifications.createNotification(
          'small1.png',
          '查到你妹啊了',
          "你所選取的文字不是個短網址吧 (｡･ω･)ﾉﾞ ｺﾝﾁｬ"
        );
      }
      notification.onclick = function(e) {
        e.currentTarget.cancel();
      };
      notification.show();
    }
  });
  
}

var parent  = chrome.contextMenus.create({
  "title": "縮網址啦～",
  "contexts": ["all"]
});

chrome.contextMenus.create({
  "title":    "反查短網址",
  "contexts": ["selection", "link"],
  "onclick":  trackShortUrl
});


for (var i in domains) {
  chrome.contextMenus.create({
    "parentId": parent,
    "title": "使用 "+domains[i],
    "contexts": ["all"],
    "onclick":  shortener_onclick
});
}